<template>
  <div>
    <a-input-search
      v-model="selectedSupplierNames"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch"
    >
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>

    <a-modal
      :title="title"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="8" :sm="12">
                <a-form-item label="供应商名称">
                  <a-input placeholder="请输入供应商名称" v-model="queryParam.supplierName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <!-- 推荐提示框 -->
        <a-alert v-if="supplierList && supplierList.length > 0" type="info" show-icon class="supplier-recommend-alert">
          <template slot="message">
            <span class="recommend-title">供应商推荐</span>
          </template>
          <template slot="description">
            <div class="recommend-description">
              系统已根据<span class="highlight-factor">价格</span>、 <span class="highlight-factor">信用等级</span>、
              <span class="highlight-factor">交货周期</span>和
              <span class="highlight-factor">最小订货量</span>
              为您推荐最优供应商
            </div>
          </template>
        </a-alert>

        <!-- 表格区域 -->
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="supplierList"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            type: internalMultiple ? 'checkbox' : 'radio',
          }"
          :customRow="customRowClick"
          :rowClassName="getRowClassName"
          @change="handleTableChange"
        >
          <template slot="materialImagesSlot" slot-scope="text">
            <div v-if="text" class="material-images-container">
              <a-carousel dots-position="bottom" arrows autoplay>
                <div v-for="(img, index) in getImagesArray(text)" :key="index" class="material-image-item">
                  <img
                    :src="getImageUrl(img)"
                    @click="handlePreviewImage(img)"
                    alt="物料图片"
                    @error="handleImageError"
                    class="material-image"
                  />
                </div>
              </a-carousel>
            </div>
            <span v-else>-</span>
          </template>

          <template slot="priceSlot" slot-scope="text">
            <span>{{ text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00' }}</span>
          </template>

          <template slot="isPreferredSlot" slot-scope="text">
            <a-tag :color="text === 1 ? 'green' : 'orange'">
              {{ text === 1 ? '是' : '否' }}
            </a-tag>
          </template>

          <template slot="creditLevelSlot" slot-scope="text">
            <a-tag :color="getCreditLevelColor(text)">
              {{ getCredutLevelText(text) || '-' }}
            </a-tag>
          </template>

          <template slot="recommendedSlot" slot-scope="text, record">
            <a-tag v-if="record.isRecommended" color="green" class="recommend-tag"> <a-icon type="like" /> 推荐 </a-tag>
            <span v-else>-</span>
          </template>
        </a-table>
      </a-spin>

      <!-- 图片预览模态框 -->
      <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
        <img alt="物料图片" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-modal>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
import { getFileAccessHttpUrl } from '@/api/manage'

export default {
  name: 'JSelectSupplierModal',
  props: {
    placeholder: {
      type: String,
      default: '请选择供应商',
      required: false,
    },
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    value: {
      type: String,
      required: false,
    },
    materialCode: {
      type: String,
      required: false,
      default: '',
    },
    multiple: {
      type: Boolean,
      default: false,
      required: false,
    },
    modalWidth: {
      type: Number,
      default: 1000,
      required: false,
    },
    title: {
      type: String,
      default: '选择供应商',
      required: false,
    },
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      loading: false,
      selectedRowKeys: [],
      selectedSupplierIds: [], // 保存选择的供应商ID
      selectedSupplierNames: '', // 保存选择的供应商名称
      selectedSuppliers: [], // 保存选择的供应商信息
      internalMultiple: this.multiple, // 内部使用的多选标志
      supplierList: [],
      modalVisible: false,
      previewVisible: false,
      previewImage: '',

      // 查询条件
      queryParam: {
        supplierName: '',
        creditLevel: '',
        materialCode: this.materialCode,
      },

      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },

      url: {
        materialSuppliers: '/wms/supplier/material/suppliers',
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '供应商名称',
          align: 'center',
          dataIndex: 'supplierName',
          width: 150,
        },
        {
          title: '物料图片',
          align: 'center',
          dataIndex: 'materialImages',
          width: 100,
          scopedSlots: { customRender: 'materialImagesSlot' },
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'materialUnit',
          width: 80,
        },
        {
          title: '价格',
          align: 'center',
          dataIndex: 'price',
          width: 100,
          scopedSlots: { customRender: 'priceSlot' },
        },
        {
          title: '信用等级',
          align: 'center',
          dataIndex: 'creditLevel',
          width: 100,
          scopedSlots: { customRender: 'creditLevelSlot' },
        },
        {
          title: '交货周期(天)',
          align: 'center',
          dataIndex: 'leadTime',
          width: 120,
        },
        {
          title: '最小订购量',
          align: 'center',
          dataIndex: 'minOrderQuantity',
          width: 120,
        },
        {
          title: '推荐',
          align: 'center',
          dataIndex: 'isRecommended',
          width: 80,
          scopedSlots: { customRender: 'recommendedSlot' },
        },
      ],
    }
  },
  watch: {
    materialCode: {
      immediate: true,
      handler(val) {
        if (val) {
          this.queryParam.materialCode = val
          // 当物料编码变化时，自动获取供应商列表
          this.loadSuppliersByMaterialCode(val)
        } else {
          this.supplierList = []
          this.selectedSupplierNames = ''
        }
      },
    },
    value: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initSelectedSupplier(val)
        } else {
          this.selectedSupplierIds = []
          this.selectedSupplierNames = ''
          this.selectedSuppliers = []
          this.selectedRowKeys = []
        }
      },
    },
  },
  methods: {
    // 根据物料编码加载供应商列表
    loadSuppliersByMaterialCode(materialCode) {
      this.loading = true
      getAction(this.url.materialSuppliers, { materialCode })
        .then((res) => {
          if (res.success) {
            let supplierList = res.result || []

            console.log('获取到供应商列表:', supplierList)

            if (supplierList && supplierList.length > 0) {
              // 根据单价、信用等级、交货周期、最小订货量进行排序
              supplierList.sort((a, b) => {
                // 首先按照价格升序排序
                if (a.price !== b.price) {
                  return a.price - b.price
                }

                // 然后按照信用等级排序（假设A > B > C > D）
                const creditRank = { A: 1, B: 2, C: 3, D: 4 }
                if (a.creditLevel !== b.creditLevel) {
                  return creditRank[a.creditLevel] - creditRank[b.creditLevel]
                }

                // 接着按照交货周期排序
                if (a.leadTime !== b.leadTime) {
                  return a.leadTime - b.leadTime
                }

                // 最后按照最小订货量排序
                return a.minOrderQuantity - b.minOrderQuantity
              })

              // 标记第一个为推荐供应商
              supplierList[0].isRecommended = true

              this.supplierList = supplierList
              this.ipagination.total = supplierList.length

              // 如果没有选择供应商，自动选择推荐供应商
              if (!this.value && supplierList.length > 0) {
                this.selectedRowKeys = [supplierList[0].id]
                this.selectedSuppliers = [supplierList[0]]
                this.selectedSupplierNames = supplierList[0].supplierName

                // 自动选择推荐供应商并触发事件
                this.$emit('input', supplierList[0].id)
                this.$emit('change', supplierList[0].id, supplierList[0])
              }
            } else {
              this.supplierList = []
              this.ipagination.total = 0
              this.$message.warning('没有找到提供该物料的供应商')
            }
          } else {
            this.supplierList = []
            this.ipagination.total = 0
            this.$message.warning(res.message || '获取供应商数据失败')
          }
          this.loading = false
        })
        .catch((error) => {
          console.error('加载供应商数据失败:', error)
          this.$message.error('获取供应商数据失败，请联系管理员')
          this.supplierList = []
          this.loading = false
        })
    },

    // 初始化已选择的供应商信息
    initSelectedSupplier(supplierId) {
      if (!supplierId) return

      // 如果供应商列表已经加载，直接从列表中查找
      if (this.supplierList && this.supplierList.length > 0) {
        const selectedSupplier = this.supplierList.find((item) => item.id === supplierId)
        if (selectedSupplier) {
          this.selectedSuppliers = [selectedSupplier]
          this.selectedSupplierIds = [selectedSupplier.id]
          this.selectedSupplierNames = selectedSupplier.supplierName
          this.selectedRowKeys = [selectedSupplier.id]
          return
        }
      }

      // 如果供应商列表未加载或未找到，重新加载供应商列表
      this.loading = true
      getAction(this.url.materialSuppliers, { materialCode: this.materialCode })
        .then((res) => {
          if (res.success) {
            const supplierList = res.result || []
            this.supplierList = supplierList

            const selectedSupplier = supplierList.find((item) => item.id === supplierId)
            if (selectedSupplier) {
              this.selectedSuppliers = [selectedSupplier]
              this.selectedSupplierIds = [selectedSupplier.id]
              this.selectedSupplierNames = selectedSupplier.supplierName
              this.selectedRowKeys = [selectedSupplier.id]
            }
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 打开选择框
    handleSearch() {
      if (this.disabled) return

      this.visible = true
      this.loadData(1)
    },

    // 加载供应商数据
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }

      const params = this.getQueryParams()
      this.loading = true

      getAction(this.url.materialSuppliers, params)
        .then((res) => {
          if (res.success) {
            let supplierList = res.result || []

            if (supplierList && supplierList.length > 0) {
              // 根据单价、信用等级、交货周期、最小订货量进行排序
              supplierList.sort((a, b) => {
                // 首先按照价格升序排序
                if (a.price !== b.price) {
                  return a.price - b.price
                }

                // 然后按照信用等级排序（假设A > B > C > D）
                const creditRank = { A: 1, B: 2, C: 3, D: 4 }
                if (a.creditLevel !== b.creditLevel) {
                  return creditRank[a.creditLevel] - creditRank[b.creditLevel]
                }

                // 接着按照交货周期排序
                if (a.leadTime !== b.leadTime) {
                  return a.leadTime - b.leadTime
                }

                // 最后按照最小订货量排序
                return a.minOrderQuantity - b.minOrderQuantity
              })

              // 标记第一个为推荐供应商
              supplierList[0].isRecommended = true

              this.supplierList = supplierList
              this.ipagination.total = supplierList.length

              // 如果没有选择供应商，自动选择推荐供应商
              if (!this.value && supplierList.length > 0 && !this.selectedRowKeys.length) {
                this.selectedRowKeys = [supplierList[0].id]
                this.selectedSuppliers = [supplierList[0]]
              }
            } else {
              this.supplierList = []
              this.ipagination.total = 0
            }
          } else {
            this.supplierList = []
            this.ipagination.total = 0
            this.$message.warning(res.message || '获取供应商数据失败')
          }
          this.loading = false
        })
        .catch((error) => {
          console.error('加载供应商数据失败:', error)
          this.$message.error('获取供应商数据失败，请联系管理员')
          this.supplierList = []
          this.loading = false
        })
    },

    // 获取查询参数
    getQueryParams() {
      const param = Object.assign({}, this.queryParam)
      return param
    },

    // 自定义行点击事件
    customRowClick(record) {
      return {
        onClick: () => {
          this.handleRowClick(record)
        },
      }
    },

    // 处理行点击事件
    handleRowClick(record) {
      // 获取当前行的key
      const rowKey = record.id

      // 根据是否多选处理不同的逻辑
      if (!this.internalMultiple) {
        // 单选模式：直接设置当前行为选中状态
        this.selectedRowKeys = [rowKey]
        this.selectedSuppliers = [record]
      } else {
        // 多选模式：切换选中状态
        const index = this.selectedRowKeys.indexOf(rowKey)
        if (index === -1) {
          // 如果未选中，则添加到选中列表
          this.selectedRowKeys.push(rowKey)

          // 检查记录是否已存在于selectedSuppliers中
          const exist = this.selectedSuppliers.some((item) => item.id === record.id)
          if (!exist) {
            this.selectedSuppliers.push(record)
          }
        } else {
          // 如果已选中，则从选中列表移除
          this.selectedRowKeys.splice(index, 1)

          // 从selectedSuppliers中移除
          const supplierIndex = this.selectedSuppliers.findIndex((item) => item.id === record.id)
          if (supplierIndex !== -1) {
            this.selectedSuppliers.splice(supplierIndex, 1)
          }
        }
      }
    },

    // 选择改变
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys

      if (!this.internalMultiple) {
        this.selectedSuppliers = selectedRows
      } else {
        // 保持已经选择的和当前页面选择的
        const selectedIds = selectedRows.map((row) => row.id)
        this.selectedSuppliers = this.selectedSuppliers.filter((item) => {
          return selectedIds.includes(item.id) || !this.supplierList.map((row) => row.id).includes(item.id)
        })

        // 添加当前页面新选择的
        selectedRows.forEach((row) => {
          const exist = this.selectedSuppliers.some((item) => item.id === row.id)
          if (!exist) {
            this.selectedSuppliers.push(row)
          }
        })
      }
    },

    // 查询按钮
    searchQuery() {
      this.loadData(1)
    },

    // 重置按钮
    searchReset() {
      this.queryParam = {
        supplierName: '',
        creditLevel: '',
        materialCode: this.materialCode,
      }
      this.loadData(1)
    },

    // 表格分页、排序、筛选变化
    handleTableChange(pagination, filters, sorter) {
      this.ipagination.current = pagination.current
      this.ipagination.pageSize = pagination.pageSize
      this.loadData()
    },

    // 确定按钮
    handleOk() {
      if (this.selectedSuppliers.length === 0) {
        this.$message.warning('请选择供应商')
        return
      }

      this.selectedSupplierIds = this.selectedSuppliers.map((item) => item.id)
      this.selectedSupplierNames = this.selectedSuppliers.map((item) => item.supplierName).join(',')

      const selectedSupplier = this.selectedSuppliers[0]
      this.$emit('input', selectedSupplier.id)
      this.$emit('change', selectedSupplier.id, selectedSupplier)

      this.handleCancel()
    },

    // 取消按钮
    handleCancel() {
      this.visible = false
    },

    // 获取表格行样式
    getRowClassName(record) {
      return record.isRecommended ? 'recommended-row' : ''
    },

    // 获取信用等级颜色
    getCreditLevelColor(level) {
      console.log('获取信用等级颜色:', level)
      switch (level) {
        case 'A':
          return 'green'
        case 'B':
          return 'cyan'
        case 'C':
          return 'orange'
        case 'D':
          return 'red'
        default:
          return 'default'
      }
    },

    // 获取信用等级文本
    getCredutLevelText(level) {
      switch (level) {
        case 'A':
          return '优秀'
        case 'B':
          return '良好'
        case 'C':
          return '一般'
        case 'D':
          return '较差'
      }
    },

    // 获取图片URL
    getImageUrl(text) {
      if (!text) return ''
      try {
        return getFileAccessHttpUrl(text)
      } catch (error) {
        console.error('获取文件URL失败:', error)
        return ''
      }
    },

    // 将图片字符串转换为数组
    getImagesArray(text) {
      if (!text) return []
      return text.split(',').filter(Boolean)
    },

    // 预览图片
    handlePreviewImage(text) {
      this.previewImage = this.getImageUrl(text)
      this.previewVisible = true
    },

    // 处理图片加载错误
    handleImageError(e) {
      console.error('图片加载失败:', e)
      e.target.src =
        ''
      e.target.alt = '图片加载失败'
    },
  },
}
</script>

<style scoped>
.query-area {
  margin-bottom: 16px;
}

.supplier-list-container {
  max-height: 500px;
  overflow-y: auto;
}

.material-images-container {
  width: 80px;
  margin: 0 auto;
}

.material-image-item {
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.material-image {
  max-width: 80px;
  max-height: 60px;
  cursor: pointer;
}

/* 推荐行样式 */
::v-deep .recommended-row {
  background-color: #f6ffed;
}

::v-deep .recommended-row:hover > td {
  background-color: #d9f7be !important;
}

/* 表格样式优化 */
::v-deep .ant-table-tbody > tr {
  cursor: pointer;
}

::v-deep .ant-table-tbody > tr:hover {
  background-color: #e6f7ff;
}

::v-deep .ant-table-tbody > tr > td {
  padding: 8px;
  vertical-align: middle;
}

::v-deep .ant-table-thead > tr > th {
  padding: 10px 8px;
  background-color: #fafafa;
}

/* 表格滚动条样式优化 */
::v-deep .ant-table-body {
  overflow-x: auto !important;
}

::v-deep .ant-table-header {
  overflow: hidden !important;
  margin-bottom: 0 !important;
  padding-bottom: 0 !important;
}

/* 推荐提示框样式 */
.supplier-recommend-alert {
  margin-bottom: 16px;
  border-radius: 4px;
}

.recommend-title {
  font-weight: 600;
  font-size: 14px;
}

.recommend-description {
  line-height: 1.5;
  margin-top: 4px;
}

.highlight-factor {
  color: #1890ff;
  font-weight: 600;
}

.recommend-tag {
  font-weight: 600;
}

/* 底部提示样式 */
.bottom-tips {
  margin-top: 16px;
  padding: 8px 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
  color: #666;
  font-size: 13px;
}
</style> 